package com.yqya.springboot.distributedlock.mysql.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yqya.springboot.distributedlock.mysql.biz.LockInfoBizService;

import lombok.extern.slf4j.Slf4j;

/**
 * 测试示例
 *
 * @author Kevin
 * @date 2019-08-03
 */
@Slf4j
@RestController
public class TestController {

    @Autowired
    private LockInfoBizService lockInfoBizService;

    @GetMapping("/try_lock")
    public Boolean tryLock(String tag, Integer expiredSeconds) {
        return lockInfoBizService.tryLock(tag, expiredSeconds);
    }

    @GetMapping("/unlock")
    public Boolean unlock(String tag) {
        lockInfoBizService.unlock(tag);
        return true;
    }

    @GetMapping("/test")
    public String test(String tag, Integer expiredSeconds) {
        boolean result = lockInfoBizService.tryLock(tag, expiredSeconds);
        if (result) {
            try {
                // do something
                // 这里使用睡眠两秒，方便观察获取不到锁的情况
                Thread.sleep(2000);
            } catch (Exception e) {
                log.error("+++++ 业务出现异常", e);
            } finally {
                lockInfoBizService.unlock(tag);
            }
            return "获取锁成功，tag是：" + tag;
        }
        return "当前tag：" + tag + "已经存在锁，请稍后重试！";
    }

}
